package com.vcredit.creditcat.manager.report;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.service.report.CustomerQualificationService;
import com.vcredit.creditcat.api.IMobileBillSummaryManager;
import com.vcredit.creditcat.model.AuthMobile;
import com.vcredit.creditcat.model.AuthProccess;
import com.vcredit.creditcat.model.CustQualificationStatistics;
import com.vcredit.creditcat.service.AuthMobileService;
import com.vcredit.creditcat.service.AuthProccessService;
import com.vcredit.creditcat.service.CustAccountService;
import com.vcredit.creditcat.service.CustQualificationStatisticsService;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.custReoprt.MobileEntityResultVo;
import com.vcredit.creditcat.vo.custReoprt.MobileResultsVo;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 手机总账单拉取 存库
 * 
 * @author chengxin
 *
 */
@Service(protocol = { "protocol1" }, version = "1.0")
public class MobileBillSummaryManager implements IMobileBillSummaryManager {
	//// 对接所用url
	@Value("${product.hl.url}")
	private String creditHLUrl;
	private static Logger logger = LoggerFactory.getLogger(MobileBillSummaryManager.class);
	@Autowired
	private CustomerQualificationService customerQualificationService;
	@Autowired
	private CustAccountService custAccountService;
	@Autowired
	private AuthMobileService authMobileService;
	@Autowired
	private CustQualificationStatisticsService custQualificationStatisticsService;
	@Autowired
	private AuthProccessService authProccessService;

	private static final Integer mobieStatus = 4;
	private final String boy = "男";
	private static final String resultNull = "{}";

	/**
	 * 1.获取手机认证用户 2. 获取参数，组装查询 3.封装数据插入或者更新
	 */
	@Override
	public void saveMobileBillSummary(Long custId) throws Exception {
		//// TODO Auto-generated method stub

		// 获取mobile数据
		AuthMobile mobileobj = new AuthMobile();
		mobileobj.setResultStatus(mobieStatus);
		List<AuthProccess> processese = authProccessService.findByCustId(custId);
		if (processese.size() > 0) {
			mobileobj.setProcessId(processese.get(0).getProccessId());

			List<AuthMobile> mobileList = authMobileService.findDistinctMobile(mobileobj);
			if (mobileList.size() > 0) {

				// 遍历集合对象
				for (AuthMobile authMobile : mobileList) {
					// 过期日期 之前
					if (ConcurrentDateUtil.getNowDate().before(ConcurrentDateUtil.getDateTime(authMobile.getExpiredTime()))) {
						// 身份证号 +手机号
						Map<String, Object> requstJson = new HashMap<String, Object>();
						requstJson.put("id", authMobile.getMobileId());
						// 处理测试服垃圾数据
						if (StringUtils.isBlank(authMobile.getMobileId())) {
							continue;
						}
						Object mobileResult = customerQualificationService.mobileBill(requstJson);
						// 返回结果 处理测试服垃圾数据
						MobileResultsVo json2Obj = JacksonUtil.Json2Obj(mobileResult.toString(), new TypeReference<MobileResultsVo>() {
						});
						if (StringUtils.isBlank(json2Obj.getResult())) {
							continue;
						}
						if (resultNull.equals(json2Obj.getResult())) {
							continue;
						}
						if ("null".equals(json2Obj.getResult())) {
							continue;
						}
						// 请求第三方接口
						MobileEntityResultVo creditCheckVo = JacksonUtil.Json2Obj(json2Obj.getResult(), new TypeReference<MobileEntityResultVo>() {
						});
						if (null != creditCheckVo) {
							AuthProccess process = authProccessService.findById(authMobile.getProcessId());
							if (null == process) {
								continue;
							}
							CustQualificationStatistics custQst = new CustQualificationStatistics();
							custQst = this.custQ(custQst, creditCheckVo);
							/** [评分_手机]最大套餐金额 **/
							custQst.setScrCellMaxPlanAmt(Utility.rounding(creditCheckVo.getMaxPlanAmt()));
							if (null != custQst) {
								custQst.setCustId(process.getCustId());
								custQst.setMobileExpiredTime(ConcurrentDateUtil.strToDate(authMobile.getExpiredTime()));

								// 查询是否存在记录
								CustQualificationStatistics custQualification = new CustQualificationStatistics();
								custQualification.setCustId(process.getCustId());
								List<CustQualificationStatistics> custQualist = custQualificationStatisticsService.find(custQualification);

								if (custQualist.size() > 0) {
									if (ConcurrentDateUtil.getDateTime(authMobile.getExpiredTime()).after(custQualist.get(0).getCreditExpiredTime())) {
										custQst.setCustStatisticsId(custQualist.get(0).getCustStatisticsId());
										custQualificationStatisticsService.update(custQst);
									}
								} else {
									custQualificationStatisticsService.insert(custQst);
								}
							}
						}
					}
				}
			}
		}
	}

	public static Integer splitTime(String time) {
		String times = "";
		if (time.contains(".")) {
			times = time.substring(0, time.indexOf("."));

		} else {
			times = time;
		}
		return Integer.parseInt(times);
	}

	public CustQualificationStatistics custQ(CustQualificationStatistics custQst, MobileEntityResultVo creditCheckVo) {
		// [手机]近1个月套餐金额 //
		custQst.setTrcLsmOneAvgPlanAmt(Utility.rounding(creditCheckVo.getLSM1_PLAN_AMT()));

		// [手机]近1个月话费总金额 //
		custQst.setTrcLsmOneAvgTotalAmt(Utility.rounding(creditCheckVo.getLSM1_TOT_AMT()));

		// [评分_手机]近180天内累计主叫套餐外话费 //
		custQst.setScrHundredEightyDaysCellCallingSubttl(Utility.rounding(creditCheckVo.getDAY180_CALLING_SUBTTL()));
		// [手机]近30天通话联系人 //
		custQst.setLdThirtyDaysTotalPplCnt(Integer.parseInt(creditCheckVo.getL30D_TOTAL_PPL_CNT()));

		// [手机]近150天通话联系人 //
		custQst.setLdHundredFiftyDaysTotalPplCnt(Integer.parseInt(creditCheckVo.getL150D_TOTAL_PPL_CNT()));

		// [评分_手机]被叫联系人个数 //
		custQst.setScrCellCalledPhoneCnt(Integer.parseInt(creditCheckVo.getCALLED_PHONE_CNT()));

		// [评分_手机]有被叫的天数 //
		custQst.setScrCellCalledCttDaysCnt(Integer.parseInt(creditCheckVo.getCALLED_CTT_DAYS_CNT()));

		// [手机]近150天短信手机联系人 //
		custQst.setSmsHundredFiftyDaysLdTtlPpl(Integer.parseInt(creditCheckVo.getSMS_L150D_TTL_PPL()));

		// [评分_手机]累计深夜通话时长(24:00-6:00)（秒） //
		custQst.setScrCellEvnCallTtlTime(splitTime(creditCheckVo.getSCR_CELL_EVN_CALL_TTL_TIME()));

		// [评分_手机]累计通话时长 //
		custQst.setScrCellCallTtlTime(splitTime(creditCheckVo.getSCR_CELL_EVN_CALL_TTL_TIME()));

		// [手机]近150天早上通话次数 //
		custQst.setLdHundredFiftyDaysSmyCttMrgCnt(Integer.parseInt(creditCheckVo.getL150D_SMY_CTT_MRG_CNT()));

		// [手机]近150天全天通话次数 //
		custQst.setLdHundredFiftyDaysCttCnt(Integer.parseInt(creditCheckVo.getL150D_SMY_CTT_CNT()));

		// [评分_手机]累计下午通话时长(13:00-18:00) //
		custQst.setScrCellAftnCallTtlTime(splitTime(creditCheckVo.getAFTN_CALL_TTL_TIME()));

		// [评分_手机]累计主叫时长 //
		custQst.setScrCellCallingTtlTime(splitTime(creditCheckVo.getCALLING_TTL_TIME()));

		// [手机]近90天工作日联系人个数 //
		custQst.setLdNinetyWeekCttPpl(Integer.parseInt(creditCheckVo.getL90D_WEEK_CTT_PPL()));

		// [手机]近90天联系人个数 //
		custQst.setLdNinetyTotalPplCnt(Integer.parseInt(creditCheckVo.getL90D_TOTAL_PPL_CNT()));

		// [手机]近90天累计主叫联系人个数 //
		custQst.setLdNinetyTcallPplCnt(Integer.parseInt(creditCheckVo.getL90D_CALL_PPL_CNT()));

		// [手机]近90天累计被叫联系人个数 //
		custQst.setLdNinetyTansTotalPpl(Integer.parseInt(creditCheckVo.getL90D_CALL_PPL_CNT()));

		// [手机]近180天主叫时长 //
		custQst.setCallHundredEightyDaysCallTime(splitTime(creditCheckVo.getCALL_D180_CALL_TIME()));

		// [手机]近180天内主叫次数 //
		custQst.setCallHundredEightyDaysLstmCallCnt(Integer.parseInt(creditCheckVo.getCALL_LSTM6_CALL_CNT()));

		// [手机]近180天被叫时长 //
		custQst.setCallHundredEightyDaysCalledTime(splitTime(creditCheckVo.getCALL_D180_CALLED_TIME()));

		// [手机]近180天被叫次数 //
		custQst.setCallHundredEightyDaysCalledCnt(Integer.parseInt(creditCheckVo.getCALL_D180_CALLED_CNT()));

		// [评分_手机]手机开卡时长至申请时间月数间隔 //
		custQst.setScrCellPhUseMons(splitTime(creditCheckVo.getPH_USE_MONS()));

		// [手机]近150天通话天数 //
		custQst.setLdHundredFiftyDaysCttDay(Integer.parseInt(creditCheckVo.getL150D_CTT_DAY()));

		// [手机]近30天累计晚间被叫次数(18:00-23:00) //
		custQst.setLdThirtyDaysSmyAnsEvngCnt(splitTime(creditCheckVo.getL30D_SMY_ANS_EVNG_CNT()));

		// [手机]近150天累计晚间被叫次数(18:00-23:00) //
		custQst.setLdHundredFiftyDaysSmyAnsEvngCnt(splitTime(creditCheckVo.getL150D_SMY_ANS_EVNG_CNT()));

		return custQst;
	}
}
